class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.where(["lower(nickname) = :value OR lower(email) = :value OR lower(rut) = :value", { :value => params[:login].downcase }]).where(:deleted=>nil).first
    if user && user.authenticate(params[:password])
      if !user.confirmation
        gflash :warning => { :value => "Contacte un administrador ",:title => "Su cuenta aun no ha sido confirmada" } 
        redirect_to root_url
      elsif user.locked or user.faild_attempts>3
        gflash :error => { :value => "Ha intentado ingresar fallidamente mas de tres veces",:title => "Su cuenta esta bloqueada temporalmente" } 
        redirect_to root_url
      elsif params[:remember_me]
        cookies.permanent[:auth_token] = user.auth_token
        gflash :success => { :value => "Bienvenido ",:title => "Ha iniciado sesion!" } 
        redirect_to profile_path(:id => user)
      else
        cookies[:auth_token] = user.auth_token
        gflash :success => { :value => "Bienvenido ",:title => "Ha iniciado sesion!" } 
        redirect_to profile_path(:id => user) 
      end
    else
      if user 
        user.update_attribute(:faild_attempts, user.faild_attempts+=1)
      end
      gflash :warning => { :value => "Vuelva a intentarlo ",:title => "Login o contrasena incorrecta!" } 
      render "new"
    end
  end

  def destroy
    cookies.delete(:auth_token)
    gflash :success => { :value => "Vuelva pronto",:title => "Ha cerrado sesion!" } 
    redirect_to root_url
  end

end
